import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import http from '@/utils/http'
import store from '@/store'
import manageRoute from './manageRoute'
///同步加载组件
const router = createRouter({
    //路由配置
    history: createWebHashHistory(),
    routes: [
        {
            name: "Index",
            path: "/",
            redirect: '/manage',//重定向
            meta: {//路由元信息. 可以在定义路由的时候 往路由里面传值.
                title: "首页"
            },
            children: [//路由嵌套
                {
                    ...manageRoute
                }
            ]
        },
        {
            name: "Login",//具名路由 可以根据名称跳转
            path: '/login',
            component: () => import("@view/Login.vue") //vue路由里面路由组件懒加载
        },
        { path:"/reg",component:()=>import("@view/Reg.vue")},
        { path:"/findpass",component:()=>import("@view/FindPass.vue")},
        {
            path: "/:nomatch(.*)*",
            component: () => import("@view/404.vue")
        }
    ],
});
router.beforeEach(async (to, from, next) => {
    // let token = localStorage.getItem("Authorization");
    // console.log("stores===>",store.getters.isLogin)
    if(store.getters.isLogin){//如果登录
       let token=store.state.Authorization;
       let re= await http.get("/user/verify",{Headers:{"Authorization":token}});
       if(re.data.data.status==400){//验证失败 去登录
            next("/login")
       }else{//验证通过
            // router.addRoute()// 添加一级路由
            if(to.path=="/login"){//如果去的登录 跳回manage
                next("/manage");
            }else{
                next();
            }
       }
    }else{
        if(to.path=="/login") next();
        // else next();//暂时放行
        else next("/login");

    }
    //校验下 token
    // let result = await http.get("/user/verify", {
    //     Headers: {
    //         "Authorization": store.state.Authorization
    //     }
    // });
    // if (result.data.data.status == 400) {
    //     next("/login");
    // }
    // else {
    //     if (to.path == "/login") {//判断如果是登录 那么路由确认放行
    //         if (token && token.length >= 10) {
    //             next("/manage")
    //         } else {
    //             next();
    //         }
    //     } else {
    //         if (!token || token.length < 10) {
    //             next("/login");
    //         } else {
    //             next();
    //         }
    //     }
    // }
});
router.beforeResolve((to, from, next) => {
    console.log("全局路由守卫函数==beforeResolve=>");
    next();
});
router.afterEach((to, from) => {//上一次路由离开
    console.log("全局路由守卫afterEach");
})

//公开router对象 router需要作为插件安装到Vue的根对象
export default router;